<template>
  <view class="bg-gray-50 min-h-screen w-[750rpx] px-[32rpx] py-[40rpx] box-border relative">
    <view class="w-full max-w-[600rpx] mx-auto pt-[80rpx]">
      <!-- Header -->
      <view class="text-center mb-[100rpx]">
        <view class="w-[160rpx] h-[160rpx] bg-gradient-to-r from-blue-500 to-cyan-400 rounded-[40rpx] flex items-center justify-center mx-auto mb-[40rpx]">
          <IconFont name="smartphone" class="text-[84rpx] text-white" />
        </view>
        <text class="text-[56rpx] text-gray-800 font-semibold mb-[20rpx] block">手机号登录</text>
        <text class="text-[30rpx] text-gray-500">未注册用户将自动创建账号</text>
      </view>
      
      <!-- Form -->
      <view class="bg-white rounded-[24rpx] overflow-hidden shadow-sm mb-[50rpx]">
        <!-- 手机号输入 -->
        <view class="flex items-center">
          <text class="text-[32rpx] text-gray-800 mx-[30rpx]">+86</text>
          <input 
            v-model="formData.phone"
            type="number" 
            class="flex-1 text-[34rpx] py-[28rpx] bg-transparent"
            placeholder="请输入手机号" 
            maxlength="11"
            @input="handlePhoneInput"
          />
        </view>

        <view class="h-[1px] bg-gray-200 mx-4"></view>
        
        <!-- 验证码输入 -->
        <view class="flex items-center px-[32rpx]">
          <input 
            v-model="formData.code"
            type="number" 
            class="flex-1 text-[34rpx] py-[28rpx] bg-transparent"
            placeholder="请输入验证码" 
            maxlength="6"
            @input="validateForm"
          />
          <nut-button 
            type="primary" 
            size="small"
            :disabled="!canGetCode || countdown > 0"
            class="px-[32rpx] py-[16rpx] rounded-[40rpx] text-[28rpx] ml-[20rpx]"
            @click="getVerificationCode"
          >
            {{ countdown > 0 ? `${countdown}秒` : (codeButtonText) }}
          </nut-button>
        </view>
      </view>
      
      <!-- 提示信息 -->
      <view 
        v-if="tipMessage"
        class="text-[26rpx] text-blue-500 px-[32rpx] py-[16rpx] bg-blue-50 rounded-[16rpx] mb-[20rpx]"
      >
        {{ tipMessage }}
      </view>
      
      <!-- 登录按钮 -->
      <nut-button 
        type="primary" 
        size="large"
        :disabled="!canLogin"
        class="w-full text-[36rpx] font-medium mt-[60rpx] h-[96rpx] rounded-[24rpx]"
        :class="canLogin ? 'bg-blue-500 shadow-lg' : 'bg-gray-300'"
        @click="handleLogin"
      >
        登录 / 注册
      </nut-button>
      
      <!-- 用户协议 -->
      <view class="text-center mt-[60rpx] text-[26rpx] text-gray-500">
        <text>登录即代表同意 </text>
        <text class="text-blue-500" @click="showUserAgreement">用户协议</text>
        <text> 和 </text>
        <text class="text-blue-500" @click="showPrivacyPolicy">隐私政策</text>
      </view>
    </view>
    
    <!-- Footer -->
    <view class="absolute bottom-[40rpx] left-0 right-0 text-center text-[26rpx] text-gray-500">
      ©2023 智能开发平台 · 安全登录
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onUnmounted } from 'vue'
import Taro from '@tarojs/taro'
import { post } from '@/utils/request'
import { useUserStore } from '@/store/user'

const userStore = useUserStore()

// 表单数据
const formData = reactive({
  phone: Taro.getStorageSync('phone') || '',
  code: ''
})

// 状态
const tipMessage = ref('提示：未注册的手机号将自动注册并登录')
const countdown = ref(0)
const codeButtonText = ref('获取验证码')

// 定时器
let countdownTimer: NodeJS.Timeout | null = null

// 验证手机号格式
const isValidPhone = computed(() => {
  return /^1[3-9]\d{9}$/.test(formData.phone)
})

// 验证验证码格式
const isValidCode = computed(() => {
  return /^\d{6}$/.test(formData.code)
})

// 是否可以获取验证码
const canGetCode = computed(() => {
  return isValidPhone.value && countdown.value === 0
})

// 是否可以登录
const canLogin = computed(() => {
  return isValidPhone.value && isValidCode.value
})

// 处理手机号输入
const handlePhoneInput = () => {
  const phone = formData.phone
  
  if (phone.length > 0 && !isValidPhone.value) {
    tipMessage.value = '请输入正确的手机号码'
  } else if (phone.length === 0) {
    tipMessage.value = '提示：未注册的手机号将自动注册并登录'
  } else {
    tipMessage.value = ''
  }
  
  validateForm()
}

// 验证表单
const validateForm = () => {
  // 触发计算属性更新
}

// 获取验证码
const getVerificationCode = () => {
  if (!isValidPhone.value) {
    tipMessage.value = '请输入正确的手机号码'
    return
  }

  Taro.setStorageSync('phone', formData.phone)
  
  // 开始倒计时
  countdown.value = 60
  codeButtonText.value = '重新获取'
  
  countdownTimer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      if (countdownTimer) {
        clearInterval(countdownTimer)
        countdownTimer = null
      }
    }
  }, 1000)
  
  // 显示发送成功提示
  tipMessage.value = `验证码已发送至 ${formData.phone}，请注意查收`

  post('/login/texting', {
    phone: formData.phone
  }).then(res => {
    console.log("res", res);
    formData.code = res.data
  })
  
  // 模拟自动填写验证码（测试用）
  // setTimeout(() => {
  //   formData.code = '123456'
  //   validateForm()
  // }, 1000)
  
  Taro.showToast({
    title: '验证码发送成功',
    icon: 'success'
  })
}

// 登录处理
const handleLogin = () => {
  if (!isValidPhone.value) {
    tipMessage.value = '请输入正确的手机号码'
    return
  }
  
  if (!isValidCode.value) {
    tipMessage.value = '请输入6位验证码'
    return
  }
  
  tipMessage.value = '登录中，请稍候...'

  post('/login/index', {
    phone: formData.phone,
    code: formData.code,
    // "phone": "13268196909",
    // "code": "317155",
    // "password": "b28bldyY6KoqlQH",
    // "recommendCode": "64"
  }).then(res => {
    console.log("res", res);
    if(res.code == 0){
      Taro.setStorageSync('token', res.data)
      userStore.fetchUserInfo()
      Taro.navigateTo({
        url:'/pages/home/home',
      })
    }
    Taro.showToast({
      title: res.message,
      icon: 'none',
      duration: 2000
    })
    // Taro.setStorageSync('token', res.data)
    // userStore.fetchUserInfo()

  })
  
}

// 显示用户协议
const showUserAgreement = () => {
  Taro.showModal({
    title: '用户协议',
    content: '这里是用户协议的内容...',
    showCancel: false,
    confirmText: '知道了'
  })
}

// 显示隐私政策
const showPrivacyPolicy = () => {
  Taro.showModal({
    title: '隐私政策',
    content: '这里是隐私政策的内容...',
    showCancel: false,
    confirmText: '知道了'
  })
}

// 组件卸载时清理定时器
onUnmounted(() => {
  if (countdownTimer) {
    clearInterval(countdownTimer)
  }
})

// 初始化提示
setTimeout(() => {
  tipMessage.value = '提示：未注册的手机号将自动注册并登录'
}, 1000)
</script>